package com.meihua.baoleyi.ui;

/**
 * Created by liming on 2017/10/16.
 * 登入
 */

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.common.PrefsHelper;
import com.meihua.baoleyi.model.LoginInfo;
import com.meihua.baoleyi.net.LoginC;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.StringUtils;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.utils.UrlContants;
import com.meihua.baoleyi.view.CatLoadingView;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

import static com.meihua.baoleyi.utils.StringUtils.isOrderNumeric;
import static com.meihua.baoleyi.utils.StringUtils.isOrderNumeric_;


public class LoginActivity  extends BaseActivity implements View.OnClickListener {
    private EditText et_input_username, et_pwd_userpwd;
    private static Toast toast;
    private LoginC mLoginPresenter;
    private CatLoadingView date;
    private String username;
    String pwd;
    private String id;
    private int type = -1;
    private LoginInfo loginInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        init();
    }
    private void init() {
        et_input_username = (EditText) findViewById(R.id.et_input_username);
        et_pwd_userpwd = (EditText) findViewById(R.id.et_pwd_userpwd);
        type = getIntent().getIntExtra("type", -1);
        findViewById(R.id.forget_pwd).setOnClickListener(this);
        findViewById(R.id.register).setOnClickListener(this);
        findViewById(R.id.login_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });

        //判断是否已经登入过
        if (PrefsHelper.getLoginFlag() && !PrefsHelper.getLoginInfo().isEmpty()) {
            saveAndLogin(PrefsHelper.getLoginInfo());
        }
    }

    /**
     * 登入
     * @param s
     */
    private void saveAndLogin(String s) {
        LoginInfo loginInfo = NetHelper.getBeanForJson(LoginInfo.class, s);
        myApp.setToken(loginInfo.getToken()+"");
        myApp.setLevel(loginInfo.getLevel());
        myApp.setUser_id(loginInfo.getId()+"");
        myApp.setPhone(loginInfo.getPhone()+"");
        myApp.setReal_name(loginInfo.getReal_name());//真实姓名
        myApp.setUname(loginInfo.getUname());//用户名
        myApp.setStatus(loginInfo.getStatus());//用户状态 1=>正常 -1=>禁用
        if (loginInfo.getBlocking() == 400) {
            Toast.makeText(LoginActivity.this, "您的账号已经被冻结,请购买商品进行解封", Toast.LENGTH_LONG).show();
        }
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forget_pwd://忘记密码
              startActivity(new Intent(this, FindPwdActivity.class));
                break;
            case R.id.register://注册
                startActivity(new Intent(this, RegisterActivity.class));
                break;
        }
    }

    /**
     * 点击登入
     */
    private void login() {
         username = et_input_username.getText().toString().trim();
         pwd = et_pwd_userpwd.getText().toString().trim();
        if (isEmpty(username)) {
            showShortCenter(this, R.string.input_phone_num);
            et_input_username.requestFocus(View.FOCUS_RIGHT);
            return;
        } else if (isEmpty(pwd)) {
            showShortCenter(this, R.string.input_pwd);
            et_pwd_userpwd.requestFocus(View.FOCUS_RIGHT);
            return;
        }
//        if (pwd.length() < 8) {
//            Toast.makeText(LoginActivity.this, "密码长度不小于8", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (StringUtils.isAllNum(pwd)) {
            Toast.makeText(LoginActivity.this, "不能输入纯数字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isAllCode(pwd)) {
            Toast.makeText(LoginActivity.this, "不能输入纯字母", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.equalStr(pwd)) {
            Toast.makeText(LoginActivity.this, "不能全是相同的数字或者字母", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isOrderNumeric(pwd) || isOrderNumeric_(pwd)) {
            Toast.makeText(LoginActivity.this, "不能是连续的数字--递增或递减", Toast.LENGTH_SHORT).show();
            return;
        }
        if (date == null) {
            date = new CatLoadingView();
        }
        date.show(getSupportFragmentManager(), "");
        clickLogin();

    }
    //登录
    private void clickLogin() {
        OkGo.post(UrlContants.LOGIN)
                .tag(this)
                .params("user_phone",username)
                .params("user_password", pwd)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        JSONObject object;
                        try {
                            object = new JSONObject(s);
                            if (object.optString("code").equals("200")) {
                                String data = object.optString("data");
                                //保存登入信息
                                PrefsHelper.setLoginInfo(data);
                                saveAndLogin(data);
                                date.dismiss();
                            } else {
                                ToastUtil.show(LoginActivity.this, object.optString("msg"));
                                date.dismiss();
                            }
                        } catch (JSONException e) {

                        }

                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });

    }

    /**
     * 判断是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim()) || "null".equals(str);
    }
    public static void showShortCenter(Context context, int content) {
        if (toast == null) {
            toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            toast.setText(content);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }
        toast.show();
    }
}
